<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门管理</title>
    <title>vue-demo1</title>
    <script src="/js/vue.js"></script>
    <link rel="stylesheet" href="/css/index.css">
    <script src="/js/index.js"></script>
    <script src="/js/axios.min.js"></script>
</head>
<body>
<div id="app">
    <!--查询-->
    <el-row>
        <el-col :span="4"><el-input  v-model="searchForm.deptN"  size="small" placeholder="请输入部门名称"></el-input></el-col>
        <el-col :span="4"><el-input v-model="searchForm.locA"  size="small" placeholder="请输入位置"></el-input></el-col>
        <el-col :span="4"><el-button type="primary" @click="search" size="small" icon="el-icon-search">搜索</el-button></el-col>
        <el-col :span="4"><el-button type="success" round @click="handlerAdd"  size="small" icon="el-icon-circle-plus">添加</el-button></el-col>
        <el-col :span="4"></el-col>
        <el-col :span="4"></el-col>
    </el-row>
    <!--表格显示-->
    <el-table
            :data="tableData"
            style="width: 100%"
             style="height: 100%">
        <el-table-column
                prop="userId"
                width="150px"
                label="用户编号">
        </el-table-column>
<!--        <el-table-column
                prop="deptId"
                width="150px"
                label="部门编号">
        </el-table-column>-->
        <el-table-column
                prop="loginName"
                width="150px"
                label="名称">
        </el-table-column>
        <el-table-column
                prop="userName"
                width="150px"
                label="账号">
        </el-table-column>
<!--        <el-table-column
                prop="userType"
                width="150px"
                label="唯一识别">
        </el-table-column>-->
        <el-table-column
                prop="email"
                width="200px"
                label="邮箱">
        </el-table-column>
        <el-table-column
                prop="phonenumber"
                width="180px"
                label="电话">
        </el-table-column>
        <el-table-column
                prop="sex"
                width="150px"
                label="性别编号">
            <!--三元判断 性别男 其他为性别女-->
            <template slot-scope="scope">
                <el-tag
                        :type="scope.row.sex == 0 ? 'success' : 'danger'"
                        disable-transitions>{{scope.row.sex == 0 ? "男" : "女"}}
                </el-tag>
            </template>
        </el-table-column>
<!--        <el-table-column
                prop="password"
                width="150px"
                label="密码">
        </el-table-column>-->

        <el-table-column label="操作" width="250px" fixed="right">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        type="info" round
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                        size="mini"
                        type="danger" round
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                <el-button
                        size="mini"
                        type="primary" round
                        @click="limit(scope.$index, scope.row)" width="200px">授权</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[2,5,10,15,20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>
    <!--更新对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules">
            <el-form-item label="名称" :label-width="formLabelWidth">
                <el-input v-model="form.loginName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="账号" :label-width="formLabelWidth">
                <el-input v-model="form.userName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                <el-input v-model="form.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机号" :label-width="formLabelWidth" prop="phonenumber">
                <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
                <el-input v-model="form.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth">

                <el-select v-model="form.sex" placeholder="请选择性别">
                    <el-option label="男" value="0"></el-option>
                    <el-option label="女" value="1"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
        </div>
    </el-dialog>

    <!--分配角色的对话框-->
    <el-dialog
            title="分配角色"
            :visible.sync="dialogVisible"
            width="30%"
    >
        <el-checkbox-group v-model="checkedRole">
            <!--<el-checkbox lable="all" @change="handleSelectAll">全选</el-checkbox>-->
            <el-checkbox v-for="role in roleList" :label="role.roleId" :key="role.roleId">{{role.roleName}}
        </el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmRole">确 定</el-button>
  </span>
    </el-dialog>

</div>
<script>
    //Vue.component();  //组件->模板
    var app = new Vue({
            el:"#app",
            //存放所有js对象的  plain  javascript object
            data(){
                return{
                  /*  rules: {
                        mobile: [
                            // 添加正则表达式 pattern: /^1[3|5|7|8|9]\d{9}$/，验证手机号是否正确
                            { required: true, message: '请输入手机号', trigger: 'change' },
                            { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' }
                        ]
                    },*/
                    handleSelectAll:null,
                    tableData: [], //表格数据
                    currentPage: 1,//当前页 第几页
                    pageSize: 15,//每页显示数量
                    total: 400,//总条数
                    searchForm:{deptN:'',locA:''},//搜索对象
                    title: '部门添加', //弹出框标题
                    dialogFormVisible: false,//对话框是否显示
                    dialogVisible:false,
                    checkedRole:[],
                 /*   checkedRoles:[],*/
                    roleList:[],
                    checkAll: false, //是否全选
                    roleIds: "",//定义所有选中角色id集合
                    checkedRoles: [], //默认选中的角色
                    userId:0,
                    form: { //form表单对象
                        loginName: '',
                        userName: '',
                        email: '',
                        phonenumber: '',
                        sex: '',
                        password: '',
                    },
                    rules:{
                        email: [
                            {required: true, message: '请输入邮箱(必填项)', trigger: 'blur'},
                            {type: 'email', message: '请输入正确的邮箱格式,比如xxx@xxx.com', trigger: ['blur', 'change']}
                        ],
                        //手机验证
                        phonenumber: [
                            {required: true, message: '请输入手机号码(必填项)', trigger: 'blur'},
                            {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的11位手机号码', trigger: ['blur', 'change']}
                        ]
                    },
                    formLabelWidth: '120px', //form中label的宽度
                }
            },
        created(){
            //用户一开始就加载，分页
            this.loadDate();
            //获取所有的角色
            this.getHaveRole();
        },
            //所有页面元素触发的事件的方法
            methods:{

                /*
                * 确认分配角色
                *
                * */
                confirmRole() {
                    // 判断是否有选择的角色
                    if (this.checkedRole.length === 0) {
                        this.$message.error('错了哦，这是一条错误消息');
                       /* this.dialogVisible = false;*/
                        /*this.deleteUserRole();*/ // 调用删除用户角色的方法
                        return;
                    }
                    var _this = this;
                    axios.post("/sysuser/confirmRole?userId=" + this.userId, this.checkedRole)
                        .then(function (response) {
                        _this.$message.success(response.data.message)
                        _this.dialogVisible = false;
                        // 获取已关联的角色
                        this.getHaveRole();

                    })
                },
                 //删除用户的角色
                deleteUserRole() {
                    var _this = this;
                    axios.delete("/sysuser/deleteUserRole?userId=" + this.userId).then(function (response) {
                        //提示信息
                        _this.$message({
                            message: '已取消用户角色！',
                            type: 'success'
                        });
                    });
                },


                getHaveRole() {
                    var _this = this;
                    // 使用axios向后台发请求
                    axios.post("/role/queryByPage",
                        {"pageNo": 1, "pageSize": 100})
                        .then(function (response) { //回调函数
                            console.log(response);//前端控制台打印
                            //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
                            if (response.data.code == 200) {
                                _this.roleList = response.data.data.list;
                            } else {
                                _this.$message.error('执行失败');
                            }
                        })
                        .catch(function (error) {//异常处理
                            console.log(error);
                        });
                },
                /**
                 * 权限赋值
                 * @param row
                 */
                limit(index, row) {
                    //定义变量
                    tempUserId = row.userId;
                    this.dialogVisible = true; //让对话框显示
                    this.getHaveRole()
                    this.userId=row.userId;
                    //定义变量
                    tempUserId = row.userId;
                    var _this = this;
                    // 使用axios向后台发请求
                    axios.get("/role/queryById?userId=" + row.userId).then(function (response) { //回调函数
                        //alert(response);//前端控制台打印，response是json对象
                        if (response.data.code == 200) {
                            _this.checkedRole = [];
                            for (var i = 0; i < response.data.data.length; i++) {
                                //把查询到的角色添加到集合里
                                _this.checkedRole.push(response.data.data[i].roleId);
                                console.log(JSON.stringify(_this.checkedRole));
                            }
                        } else {
                            _this.$message.error('执行失败');
                        }
                    })
                        .catch(function (error) {//异常处理
                            console.log(error);
                        });
                },


                //封装的加载数据方法
                loadData(){
                    //定义一个变量，赋值为当前vue对象
                    var _this = this;
                    //使用axios向后台发请求，获取数据
                    //axios.post('http://172.16.7.66:8080/dept/queryByPage', {
                    axios.post(//请求方式，必须和后端资源暴露方式一致
                        '/sysuser/queryByPage',//请求的url
                        {"pageNo":this.currentPage,"pageSize":this.pageSize,

                             "data":{"deptName":this.searchForm.deptN,"loc":this.searchForm.locA}}) //请求携带的参数


                        .then(function (response) {//成功响应的处理方法   response 是响应的数据
                            console.log(response);
                            //response 一定是json对象  stringify 把json对象转json字符串
                            //alert(JSON.stringify(response));
                            //判断返回是否正确
                            if(response.data.code==200){
                                //直接使用this 代表axios的对象  this
                                _this.tableData=response.data.data.list;
                                _this.total=response.data.data.total;
                            }else{
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                },
                //处理每页数量发生变化
                handleSizeChange(val) {
                    console.log(`每页 ${val} 条`);
                    //让每页数量发生改变
                    this.pageSize=val;
                    //调用加载数据方法
                    this.loadData();
                },
                //处理当前页（页码 第几页）发生变化
                handleCurrentChange(val) {
                    console.log(`当前页: ${val}`);
                    //让第几页发生改变
                    this.currentPage=val;
                    //调用加载数据方法
                    this.loadData();
                },
                //按条件查询
                search(){
                    //直接调用loadData
                    this.loadData();
                },
                //处理添加
                handlerAdd(){
                    //修改标题
                    this.title='添加';
                    //清空原来的值
                    this.form={};
                    //让对话框显示
                    this.dialogFormVisible = true;
                },
                //权限授权
                authorization(){
                    //修改标题
                    this.title='授权';
                    //让对话框显示
                    this.dialogVisible = true;
                },

                //处理更新
                handleEdit(index, row) {
                    console.log(index, row);
                    //alert(index+"--------"+JSON.stringify(row));
                    //row当前行数据 是json数据
                    //修改标题为 部门更新
                    this.title='部门更新';
                    //row = {"deptNo":101,"deptName":"开发部","loc":"郑州"}
                    //过去让数据回显 要调用后台queryById  现在不用  可以拿到该行数据
                    /*  form: { //form表单对象
                          deptName: '',
                              loc: '',
                      },*/
                    //{deptName: '',loc: '',}={"deptNo":101,"deptName":"开发部","loc":"郑州"}
                    this.form=row;
                    //alert(JSON.stringify(this.form));
                    //让对话框显示
                    this.dialogFormVisible = true;
                },
                //调用接口添加或者更新数据
                addOrUpdate(){
                    //定义url
                    var url = "/sysuser/add";
                    //判断是否添加还是更新
                    if(this.title==='部门更新'){
                        url = "/sysuser/update";
                    }
                    //定义一个变量，赋值为当前vue对象
                    var _this = this;
                    //使用axios向后台发请求，获取数据
                    //axios.post('http://172.16.7.66:8080/dept/queryByPage', {
                    axios.put(//请求方式，必须和后端资源暴露方式一致
                        url,//请求的url
                        this.form)//请求携带的参数  this.form={"deptNo":101,"deptName":"开发1部","loc":"郑1州"}
                        .then(function (response) {//成功响应的处理方法   response 是响应的数据
                            console.log(response);
                            //response 一定是json对象  stringify 把json对象转json字符串
                            //alert(JSON.stringify(response));
                            //判断返回是否正确
                            if(response.data.code===200){
                                //提示信息
                                _this.$message({
                                    message: '恭喜你，这是一条成功消息',
                                    type: 'success'
                                });
                                //关闭对话框
                                _this.dialogFormVisible = false;
                                //重新加载数据
                                _this.loadData();
                            }else{
                                _this.$message.error('错了哦，这是一条错误消息');
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                },
                //处理删除
                handleDelete(index, row) {
                    this.$confirm('此操作将永久删除该数据，是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        axios.delete('/sysuser/deleteById', {params: {userId: row.userId}}).then(response => {
                            if (response.data.code == 200) {
                                this.loadData();
                                this.$message.success('删除成功了')
                            } else {
                                this.$message.success('删除失败了')
                            }
                        }).catch(function (error) {
                            console.log(error);
                            this.$message.success('删除失败了')
                        });
                    })}
            },
          /*  beforeCreate(){
               alert("创建前----");
            },*/
            created(){//初始化操作
                //alert("创建后----");
                this.loadData()
            },
        }
    )
</script>
</body>
</html>
